package com.wlyuan.open.scanner.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.wlyuan.open.scanner.application.interceptor.DataScopePermissionHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author lijing
 * @description
 */
@Configuration
@MapperScan(basePackages = {"com.wlyuan.open.scanner.dao.mapper"}, sqlSessionFactoryRef = "ReadFactory")
public class ScannerDaoConfiguration {
    @Autowired
    private DataScopePermissionHandler dataScopePermissionHandler;

    /**
     * 封装数据源对象创建, 该方法就已经将数据源的各个数据封装到该对象中
     *
     * @return
     */
    @Bean(name = "ReadDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.read")
    public DataSource wlyDataSource() {
        return new DruidDataSource();
    }

    /**
     * SqlSession对象创建
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "ReadFactory")
    @Primary
    public SqlSessionFactory wlyFactory(@Qualifier("ReadDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.wlyuan.open.scanner.dao.entity");
        bean.setDataSource(dataSource);
        bean.setPlugins(mybatisPlusInterceptorRead());
        return bean.getObject();
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptorRead() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 方言
        paginationInnerInterceptor.setDbType(DbType.SQL_SERVER);
        paginationInnerInterceptor.setMaxLimit(1000L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);

        /*DataPermissionInterceptor dataPermissionInterceptor = new DataPermissionInterceptor();
        dataPermissionInterceptor.setDataPermissionHandler(dataScopePermissionHandler);
        interceptor.addInnerInterceptor(dataPermissionInterceptor);*/
        return interceptor;
    }
}
